package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.pojo.SysUserDept;
import com.cy.pj.sys.service.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;


    @Override
    public PageObject<SysUserDept> findPageObjects(String username, Integer pageCurrent) {
        if(pageCurrent==0 || pageCurrent<1)
            throw new IllegalArgumentException("当前页码值无效");
        int rowCount = sysUserDao.getRowCount(username);
        if(rowCount == 0){
            throw new ServiceException("没有找到对应的记录");
        }
        Integer pageSize = 6;
        Integer startIndex = (pageCurrent-1)*pageSize;
        List<SysUserDept> records = sysUserDao.findPageObjects(username, startIndex, pageSize);
        System.out.println(records);
        return new PageObject<>(pageCurrent, pageSize, rowCount, records);
    }

    @RequiredLog(operation = "分页查询用户信息")
    @Override
    public PageObject<SysUserDept> findPageObjects2(String username, Integer pageCurrent) {
        if(pageCurrent==0 || pageCurrent<1)
            throw new IllegalArgumentException("当前页码值无效");
        int pageSize = 6;
        Page<SysUserDept> page = PageHelper.startPage(pageCurrent, pageSize);
        List<SysUserDept> records = sysUserDao.findPageObjects2(username);
        return new PageObject<>(pageCurrent, pageSize, (int) page.getTotal(), records);
    }

    @RequiredLog(operation = "启用/禁用用户")
    @Override
    public int validById(Integer id, Integer valid) {
        //1.合法性验证
        if(id==null||id<=0)
            throw new ServiceException("参数不合法,id="+id);
        if(valid==null||(valid!=1&&valid!=0))
            throw new ServiceException("参数不合法,valid="+valid);
        //2.执行禁用或启用操作(admin 为后续登陆用户）
        int rows=sysUserDao.validById(id, valid,"admin");
        //3.判定结果,并返回
        if(rows==0)
            throw new ServiceException("此记录可能已经不存在");
        return rows;
    }

    @Transactional
    @Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        //1.参数校验
        if(entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if(StringUtils.isEmpty(entity.getPassword()))
            throw new IllegalArgumentException("密码不能为空");
        if(roleIds==null || roleIds.length==0)
            throw new IllegalArgumentException("至少要为用户分配角色");
        //2.保存用户自身信息
        //2.1 对密码进行加密
        String salt = UUID.randomUUID().toString();
        SimpleHash sh = new SimpleHash("MD5", entity.getPassword(), salt, 1);
        String hashPassword = sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(hashPassword);
        int rows = sysUserDao.insertObject(entity);
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        return rows;
    }

    @Override
    public Map<String, Object> findById(Integer id) {
        SysUserDept user = sysUserDao.findById(id);
        if(user==null)
            throw new ServiceException("用户可能已经不存在");
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(id);
        Map<String,Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roleIds", roleIds);
        return map;
    }

    @Override
    public int updateObject(SysUser entity, Integer[] roleIds) {
        //1.参数校验
        if(entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if(StringUtils.isEmpty(entity.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if(roleIds==null || roleIds.length==0)
            throw new IllegalArgumentException("至少要为用户分配角色");
        //2.保存用户自身信息
        //2.1 对密码进行加密
        int rows = sysUserDao.updateObject(entity);
        sysUserRoleDao.deleteObjectsByUserId(entity.getId());
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        return rows;
    }
}
